package oop.controller.action.question;

import java.sql.SQLException;

import oop.controller.action.DefaultAction;
import oop.data.Answer;
import oop.db.dao.AnswerDAO;
import oop.db.dao.QuestionAnswerDAO;

import org.apache.commons.lang.StringUtils;

public class AddAnswerAction extends DefaultAction {

	@Override
	public void performImpl() throws Exception {
		title("Thêm câu trả lời");
		String submit = request.getParameter("qa_submit");
		if ("add".equals(submit)) {
			try {
				int questionId = Integer.parseInt(request
						.getParameter("qa_question"));
				String ans = request.getParameter("answer");
				boolean correct = !StringUtils.isEmpty(request
						.getParameter("correct"));
				Answer answer = AnswerDAO.create(ans, 1, getUser().getId());
				QuestionAnswerDAO
						.addAnswer(questionId, answer.getId(), correct);
				
				boolean more = !StringUtils.isEmpty(request.getParameter("qa_more"));
				if (more) {
					request.setAttribute("qa_clear", true);
				} else {
					setNextAction("question.view&qv_id=" + questionId);
				}
			} catch (NumberFormatException ex) {
				request.setAttribute("idErr", "Định dạng không hợp lệ");
			} catch (SQLException ex) {
				if (ex.getErrorCode() == 1452) {
					request.setAttribute("idErr",
							"Không tồn tại câu hỏi với ID "
									+ request.getParameter("questionId"));
				}
			}
		}
	}
}
